# -*- coding: utf-8 -*-

import bs4
import requests
import time

url_status = "http://acm.hdu.edu.cn/status.php"

finish_status = ["Accepted", "Wrong Answer", "Presentation Error", 
			  "Compilation Error", "Runtime Error", "Time Limit Exceeded", 
			  "Memory Limit Exceeded", "Output Limit Exceeded"]

def check(results):
	if len(results) < 9:
		return False
	elif len(results) == 10:
		results[2] = results[2] + " " + results[3]
		results.pop(3)
	for item in finish_status:
		if results[2].startswith(item):
			return True
	return False

def get_results(session, status_data):
	resp = session.get(url_status, params=status_data)
	page = resp.content
	handler = bs4.BeautifulSoup(page)	
	BODY = handler.body
	TABLE = BODY.table
	TR = TABLE.findAll('tr', align='center')
	results = list(TR[2].strings)
	if check(results) == False:
		return 1, None
	return 0, results
		

def get_status(user_id):
	session = requests.session()
	status_data = { 'user' : user_id }
	for ith in range(5):
		time.sleep(2)
		res, results = get_results(session, status_data)
		if res == 0: 
			stream = "%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s" \
					  % ("0", "Success", results[0], results[1],\
					  results[8], results[3], results[2], results[7], \
					  results[4], results[5], results[6])
			return stream
	
	stream = "%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s" \
			  % ("1", "Parse Failed", "-", "-", "-", "-", "-", "-", "-", "-", "-")
	return stream

if __name__ == '__main__':
	print get_status("gvj3")
